﻿package com.kuanter.kuanterauto.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kuanter.auto.sns.CallBack;
import com.kuanter.auto.sns.SNS;
import com.kuanter.auto.sns.TX;
import com.kuanter.auto.sns.XL;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.adapter.CarListAdapter;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.cache.ObjectCache;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.UserInfo;
import com.kuanter.kuanterauto.entity.VehicleInfo;
import com.kuanter.kuanterauto.main.HomeActivityGroup;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.share.WeixinShareUtil;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SendSmsUtil;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtil;
import com.kuanter.kuanterauto.wxapi.WXEntryActivity;
import com.tencent.mm.sdk.openapi.BaseReq;
import com.tencent.mm.sdk.openapi.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.net.RequestListener;

public class VipCenterActivity extends WuyangBaseActivity implements CallBack ,IWXAPIEventHandler{

	private Intent intent = new Intent();
	private TextView account_name_title;
	private TextView account_name_data;
	private View personal_info_goto;
	private View my_consumer_log_goto;
	private View my_kuanter_card_goto;
	private View my_car_goto;
	private View recharge_goto;
	private View activate_card_goto;
	private View share_btn;
	SNS tx;
	SNS xl;
	private String share_content;

	private UserInfo userInfo;
	private TextView logout_tv;
	private IWXAPI api;
	private TextView save_money_tv;
	private int userId;
	private String saveMoney = "0.00";
	
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
							JSONObject jsonObject = JSON.parseObject(result);
							saveMoney = jsonObject.getString("savedMoney");
//							application.setSaveMoney(saveMoney);
							save_money_tv.setText(saveMoney);
						} else {
							
						}
					} catch (JSONException e) {
						Toast.makeText(VipCenterActivity.this,"登录失败", 0).show();
						e.printStackTrace();
					}
				} else {
					Toast.makeText(VipCenterActivity.this, "登录失败,网络错误!", 0).show();
				}
				break;
			case HttpTask.RESULT_ERROR:  
				Toast.makeText(VipCenterActivity.this, "网络错误!", 0).show();
				break;
			}
		}
	};
	private ProApplication application;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.vip_center);
		
		
			xl = new XL(VipCenterActivity.this, MainConstants.XL_KEY, MainConstants.XL_URL);
			xl.regCallback(VipCenterActivity.this);
			tx = new TX(this, MainConstants.TX_KEY, MainConstants.TX_SCREAT,
					"null");
			tx.regCallback(this);
			api = WXAPIFactory.createWXAPI(this, WeixinShareUtil.AppID, false);
	    	api.registerApp(WeixinShareUtil.AppID);
	    	api.handleIntent(getIntent(), this);
	    	
		application = (ProApplication)getApplication();
		userId = SharePrefenceUtil.getUserID(this);
		 // 通过WXAPIFactory工厂，获取IWXAPI的实例
    	
		/*
		 * StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.
		 * Builder().detectDiskReads().detectDiskWrites().
		 * detectNetwork().penaltyLog().build());
		 */

		this.initBodyControlView();
		this.setBodyControlViewText();
		this.registerListener();
		// 分享初始化
		

	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		
		setIntent(intent);
        api.handleIntent(intent, this);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			tx.activityResult(requestCode, resultCode, data);
		} catch (Exception e) {
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.personal_info_goto:
			intent.setClass(this, PersonalInfoActivity.class);
			startActivity(intent);
			break;
		case R.id.share_btn:
			// 第三方应用接口
			// showToast("第三方应用接口");
			/*AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(R.string.share);
			builder.setItems(R.array.shareTo,
					new DialogInterface.OnClickListener() {
						private WeixinShareUtil weixinShareUtil;

						public void onClick(DialogInterface dialog, int which) {
							switch (which) {
							case 0:
								xl.oAuth();
								SharePrefenceUtil.setXinlangLock(
										VipCenterActivity.this, true);
								break;
							case 1:
								tx.oAuth();
								SharePrefenceUtil.setTengxunLock(
										VipCenterActivity.this, true);
								break;
							case 2:
								weixinShareUtil = new WeixinShareUtil(VipCenterActivity.this);
								weixinShareUtil.shareText("宽途汽车");

								break;
							case 3:
								new SendSmsUtil(this).sendSms(sendToPhone, authCode);
								break;
							}
						}
					});
			builder.create().show();*/
			
			final String saveMoney = save_money_tv.getText().toString();
			Builder build = new AlertDialog.Builder(VipCenterActivity.this).setTitle("分享好友")
			.setItems(R.array.share_item, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if(which == 0) {
//						Intent intent = new Intent(Intent.ACTION_MAIN);
//						intent.addCategory(Intent.CATEGORY_DEFAULT);
//						intent.setType("vnd.android-dir/mms-sms");
						Uri uri = Uri.parse("smsto:");
						Intent intent = new Intent(Intent.ACTION_SENDTO,uri);
						intent.putExtra("sms_body", "宽途已为我节省" + saveMoney + "元");
						startActivity(intent);
						if(dialog != null) {
							dialog.dismiss();
						}
					} else if(which == 1) {
						Intent intent = new Intent(VipCenterActivity.this, WXEntryActivity.class);
						intent.putExtra("status", 2);
						intent.putExtra("friend", false);
						intent.putExtra("saveMoney", saveMoney);
						intent.putExtra("who", ShareActivity.HE);
						startActivity(intent);
						if(dialog != null) {
							dialog.dismiss();
						}
					}else if(which == 2) {
						Intent intent = new Intent(VipCenterActivity.this, WXEntryActivity.class);
						intent.putExtra("status", 2);
						intent.putExtra("friend", true);
						intent.putExtra("saveMoney", saveMoney);
						intent.putExtra("who", ShareActivity.HE);
						startActivity(intent);
						if(dialog != null) {
							dialog.dismiss();
						}
					} else if(which == 3) {
						Intent intent = new Intent(VipCenterActivity.this, ShareActivity.class);
						intent.putExtra("saveMoney", saveMoney);
						intent.putExtra("status", 0);
						intent.putExtra("who", ShareActivity.HE);
						startActivity(intent);
						if(dialog != null) {
							dialog.dismiss();
						}
					} else if(which == 4) {
						Intent intent = new Intent(VipCenterActivity.this, ShareActivity.class);
						intent.putExtra("status", 1);
						intent.putExtra("who", ShareActivity.HE);
						intent.putExtra("saveMoney", saveMoney);
						startActivity(intent);
						if(dialog != null) {
							dialog.dismiss();
						}
					}
				}
			});
			AlertDialog dialog = build.create();
			dialog.show();
			
			break;
		case R.id.my_consumer_log_goto:
			intent.setClass(this, MyKuanterConsumerActivity.class);
			intent.putExtra("userId", userInfo.getId());
			startActivity(intent);
			break;
		case R.id.my_kuanter_card_goto:
			intent.setClass(this, CardAndAccountActivity.class);
			startActivity(intent);
			break;
		case R.id.my_car_goto:
			intent.setClass(this, MyCarActivity.class);
			startActivity(intent);
			break;
		case R.id.logout_tv:
			application.setSaveMoney("");
			ObjectCache.clear();
			application.clearCache();
			ProApplication.getInstance().setUserInfo(null);
			List<VehicleInfo> list = ProApplication.getInstance().getList_vehicleInfo();
			if(list != null) {
				list.clear();
				list = null;
			}
			if(null != CarListAdapter.vehicleInfos){
				CarListAdapter.vehicleInfos.clear();
			}
			SharePrefenceUtil.clear(this);
			HomeActivityGroup.backAction = "";
			Intent intent = new Intent(MainConstants.Data_ACTION);
			sendBroadcast(intent);
			break;
		default:
			break;
		}
	}
	
	public void activateCard(View v){
		intent.setClass(this, ActivateCardActivity.class);
		startActivity(intent);
	}
	public void recharge(View v){
		intent.setClass(this, RechargeActivity.class); 
		startActivity(intent);
	}

	@Override
	protected void setHeaderControlViewText() {
		// TODO Auto-generated method stub
	}

	@Override
	protected void initBodyControlView() {
		// TODO Auto-generated method stub
		account_name_title = (TextView) this
				.findViewById(R.id.include_image_2tv_arrow_TVtitle);
		account_name_data = (TextView) this
				.findViewById(R.id.include_image_2tv_arrow_TVdate);
		personal_info_goto = this.findViewById(R.id.personal_info_goto);
		my_consumer_log_goto = this.findViewById(R.id.my_consumer_log_goto);
		my_kuanter_card_goto = this.findViewById(R.id.my_kuanter_card_goto);
		my_car_goto = this.findViewById(R.id.my_car_goto);
		recharge_goto = this.findViewById(R.id.recharge_goto);
		activate_card_goto = this.findViewById(R.id.activate_card_goto);
		share_btn = this.findViewById(R.id.share_btn);
		logout_tv = (TextView) this.findViewById(R.id.logout_tv);
		save_money_tv = (TextView)this.findViewById(R.id.save_money_tv);
//		save_money_tv.setText(0+"");
	}

	@Override
	protected void registerListener() {
		// TODO Auto-generated method stub
		personal_info_goto.setOnClickListener(this);
		my_consumer_log_goto.setOnClickListener(this);
		my_kuanter_card_goto.setOnClickListener(this);
		my_car_goto.setOnClickListener(this);
		recharge_goto.setOnClickListener(this);
		activate_card_goto.setOnClickListener(this);
		share_btn.setOnClickListener(this);
		logout_tv.setOnClickListener(this);
	}

	
	@Override
	protected void setBodyControlViewText() {
		// TODO Auto-generated method stub
		account_name_title.setText("个人信息");
		if(null == userInfo){
			UserInfo userInfo = new UserInfo();
			SharedPreferences sp = getSharedPreferences("userinfo", MODE_PRIVATE);
			String id = sp.getString("id", "-1");
			String mobileNumber = sp.getString("mobileNumber", "-1");
			String userEmail = sp.getString("userEmail", "-1");
			String userRealName = sp.getString("userRealName", "-1");
			userInfo.setId(id);
			userInfo.setMobileNumber(mobileNumber);
			userInfo.setUserEmail(userEmail);
			userInfo.setUserRealName(userRealName);
			this.userInfo = userInfo;
			account_name_data.setText("");
		}else {
			account_name_data.setText("");
		}
		if(!"".equals(application.getSaveMoney())){
			saveMoney = application.getSaveMoney();
			save_money_tv.setText(saveMoney);
		}else {
			List<NameValuePair> params1 = new ArrayList<NameValuePair>();
			params1.add(new BasicNameValuePair("userId", userId + ""));
			new DataLoader(this).DisplayData(MainConstants.HOST_test
					+ HttpConfigAPI.SAVE_MONEY, params1, handler, "", false);
		}
		
	}
	
	

	@Override
	protected void getControlViewText() {
		// TODO Auto-generated method stub

	}

	@Override
	public void toShare(int who) {
		final int index = who;
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// Get the layout inflater
		LayoutInflater inflater = this.getLayoutInflater();
		View view = inflater.inflate(R.layout.share_content, null);
		final EditText et_share_content = (EditText) view
				.findViewById(R.id.et_share_content);
		et_share_content.setText("宽途已为您节省"+saveMoney+"元");
		builder.setView(view);
		builder.setTitle("分享内容");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int id) {
				if (index == CallBack.WHO_XL) {
					share_content = et_share_content.getText().toString();
					xl.share(share_content,new RequestListener() {
						
						@Override
						public void onIOException(IOException arg0) {
							// TODO Auto-generated method stub
							
						}
						
						@Override
						public void onError(WeiboException arg0) {
							// TODO Auto-generated method stub
							
						}
						
						@Override
						public void onComplete(String arg0) {
							// TODO Auto-generated method stub
							
						}
					},true);
				} else if (index == CallBack.WHO_TX) {
					share_content = et_share_content.getText().toString();
					boolean success = tx.share(share_content,null,true);
				}
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {

			}
		});
		builder.create().show();
	}

	@Override
	public void onReq(BaseReq arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onResp(BaseResp arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void onResume() {
		MerchantTurnActivity1.sh = false;
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		MerchantTurnActivity1.sh = false;
		super.onDestroy();
	}
	

}
